
package com.android.sharecar.activity;

import com.android.sharecar.model.FavoriteAddress;
import com.android.sharecar.model.ReservationCycle;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

/**
 * 预约界面
 * 
 * @author xinyan
 * @date 2011-9-13
 */
public class ReservationActivity extends Activity {
    public static final String TAG = "ReserveActivity";

    public static final int REQUEST_CODE_ADDRESS_START = 1;

    public static final int REQUEST_CODE_ADDRESS_END = 3;

    public static final int REQUEST_CODE_CYCLE = 2;

    // Views
    private EditText mStartPlace, mEndPlace;

    private EditText mReservation; // reservation type: single or period

    private Spinner mSeats, mPickOrProvide;

    private ImageButton mStartPlaceFavorite, mEndPlaceFavorite;

    private static Button mSubmit, mRequestList;

    //
    private ReservationCycle mCycle;

    //
    private StringBuilder mDate = new StringBuilder();

    private StringBuilder mTime = new StringBuilder();

    private boolean isPaused = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reservation);
        Log.i(TAG, "onCreate");

        findViews();
        setListenerForViews();

        setTitleBar();
    }

    private void setTitleBar() {
        /*
         * MainTabWidgetActivity.mInstance.getWindow().setFeatureInt(Window.
         * FEATURE_CUSTOM_TITLE, R.layout.titilebar_reservation);
         */

        mSubmit = (Button) findViewById(R.id.reservation_btn_submit);
        mRequestList = (Button) findViewById(R.id.reservation_btn_requestList);

        Log.i(TAG, "mSubmit button: " + mSubmit.toString());
        Log.i(TAG, "mRequestList button: " + mRequestList.toString());

        mSubmit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i(TAG, "mSubmit is clicked...");
            }
        });

        mRequestList.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i(TAG, "mRequestList is clicked...");

                Intent intent = new Intent();
                intent.setClass(ReservationActivity.this, ReserveRequestListTabWidgetActivity.class);
                // intent.putExtra(StandardActivity.STATE,
                // StandardActivity.STATE_WAITING_FOR_RIDE);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
        /*
         * if (isPaused) { setTitleBar(); }
         */
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause");

        isPaused = true;
    }

    private void findViews() {
        mReservation = (EditText) findViewById(R.id.reservation_et_reservation);
        mEndPlace = (EditText) findViewById(R.id.reservation_et_endPlace);
        mStartPlace = (EditText) findViewById(R.id.reservation_et_startPlace);
        mSeats = (Spinner) findViewById(R.id.reservation_sp_seats);
        mPickOrProvide = (Spinner) findViewById(R.id.reservation_sp_pickOrTake);
        mStartPlaceFavorite = (ImageButton) findViewById(R.id.reservation_ib_startPlace_favorite);
        mEndPlaceFavorite = (ImageButton) findViewById(R.id.reservation_ib_endPlace_favorite);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.select_dialog_vacantSeatNum, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSeats.setAdapter(adapter);

        adapter = ArrayAdapter.createFromResource(this, R.array.select_dialog_pickOrProvide,
                android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mPickOrProvide.setAdapter(adapter);
    }

    private void setListenerForViews() {
        mReservation.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    new AlertDialog.Builder(ReservationActivity.this)
                            .setIcon(null)
                            .setTitle("请选择预约方式")
                            .setItems(R.array.select_dialog_reservation,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int whichButton) {
                                            Log.v(TAG, "alert dialog clicked.");

                                            if (0 == whichButton) {
                                                Log.v(TAG,
                                                        " user selected the period reservation button.");

                                                // Do something........
                                                startActivityForResult(new Intent(
                                                        ReservationActivity.this,
                                                        ReservationCyleActivity.class),
                                                        REQUEST_CODE_CYCLE);

                                                // then close it
                                                dialog.dismiss();
                                            } else if (1 == whichButton) {
                                                Log.v(TAG,
                                                        "user selected the single reservation button.");

                                                // Do something........
                                                try {
                                                    LayoutInflater factory = LayoutInflater
                                                            .from(ReservationActivity.this);
                                                    final ScrollView dialogView = (ScrollView) factory
                                                            .inflate(R.layout.dialog_date_time,
                                                                    null);

                                                    DatePicker datePicker = (DatePicker) dialogView
                                                            .findViewById(R.id.reservation_dp_date);
                                                    TimePicker timePicker = (TimePicker) dialogView
                                                            .findViewById(R.id.reservation_tp_time);

                                                    final Calendar c = Calendar.getInstance();

                                                    if (mDate.length() > 0) {
                                                        mDate.delete(0, mDate.length());
                                                    }
                                                    if (mDate.length() <= 0) {

                                                        mDate.append(c.get(Calendar.YEAR) + "/"
                                                                + (c.get(Calendar.MONTH) + 1) + "/"
                                                                + c.get(Calendar.DAY_OF_MONTH));
                                                    }
                                                    if (mTime.length() > 0) {
                                                        mTime.delete(0, mTime.length());
                                                    }
                                                    if (mTime.length() <= 0) {

                                                        mTime.append(c.get(Calendar.HOUR_OF_DAY)
                                                                + ":" + c.get(Calendar.MINUTE));
                                                    }
                                                    datePicker.init(c.get(Calendar.YEAR),
                                                            c.get(Calendar.MONTH),
                                                            c.get(Calendar.DAY_OF_MONTH),
                                                            new DatePicker.OnDateChangedListener() {

                                                                @Override
                                                                public void onDateChanged(
                                                                        DatePicker view, int year,
                                                                        int monthOfYear,
                                                                        int dayOfMonth) {
                                                                    // mReservation.append("单次预约：");
                                                                    if (mDate.length() > 0) {
                                                                        mDate.delete(0,
                                                                                mDate.length());

                                                                        if (year < c
                                                                                .get(Calendar.YEAR)
                                                                                && monthOfYear >= c
                                                                                        .get(Calendar.MONTH)) {
                                                                            mDate.append(c
                                                                                    .get(Calendar.YEAR)
                                                                                    + "/"
                                                                                    + (monthOfYear + 1)
                                                                                    + "/"
                                                                                    + dayOfMonth);
                                                                        } else if (year < c
                                                                                .get(Calendar.YEAR)
                                                                                && monthOfYear < c
                                                                                        .get(Calendar.MONTH)) {
                                                                            mDate.append(c
                                                                                    .get(Calendar.YEAR)
                                                                                    + "/"
                                                                                    + (c.get(Calendar.MONTH) + 1)
                                                                                    + "/"
                                                                                    + dayOfMonth);
                                                                        } else if (year == c
                                                                                .get(Calendar.YEAR)
                                                                                && monthOfYear < c
                                                                                        .get(Calendar.MONTH)) {
                                                                            mDate.append(year
                                                                                    + "/"
                                                                                    + (c.get(Calendar.MONTH) + 1)
                                                                                    + "/"
                                                                                    + dayOfMonth);
                                                                        } else {
                                                                            mDate.append(year
                                                                                    + "/"
                                                                                    + (monthOfYear + 1)
                                                                                    + "/"
                                                                                    + dayOfMonth);
                                                                        }

                                                                    } else {
                                                                        mDate.append(year + "/"
                                                                                + (monthOfYear + 1)
                                                                                + "/" + dayOfMonth);
                                                                    }
                                                                    Log.v(TAG, "date changed, "
                                                                            + mDate.toString());
                                                                }
                                                            });
                                                    timePicker.setIs24HourView(true);
                                                    timePicker
                                                            .setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {

                                                                @Override
                                                                public void onTimeChanged(
                                                                        TimePicker view,
                                                                        int hourOfDay, int minute) {
                                                                    if (mTime.length() > 0) {
                                                                        mTime.delete(0,
                                                                                mTime.length());
                                                                    }
                                                                    mTime.append(hourOfDay + ":"
                                                                            + minute);
                                                                    Log.v(TAG, "time changed,  "
                                                                            + hourOfDay + " : "
                                                                            + minute);
                                                                    Log.v(TAG,
                                                                            "time changed, mTime is "
                                                                                    + mTime.toString());
                                                                }
                                                            });

                                                    new AlertDialog.Builder(
                                                            ReservationActivity.this)
                                                            .setTitle("请选择时间")
                                                            .setView(dialogView)
                                                            .setPositiveButton(
                                                                    R.string.positive,
                                                                    new DialogInterface.OnClickListener() {

                                                                        @Override
                                                                        public void onClick(
                                                                                DialogInterface dialog,
                                                                                int which) {
                                                                            if (mDate.toString()
                                                                                    .length() > 0
                                                                                    && mTime.toString()
                                                                                            .length() > 0) {

                                                                                setSingleReservation();
                                                                            } else if (mDate
                                                                                    .toString()
                                                                                    .length() <= 0
                                                                                    && mTime.toString()
                                                                                            .length() > 0) {

                                                                                setSingleReservation();
                                                                            } else if (mDate
                                                                                    .toString()
                                                                                    .length() > 0
                                                                                    && mTime.toString()
                                                                                            .length() <= 0) {

                                                                                setSingleReservation();
                                                                            } else if (mDate
                                                                                    .toString()
                                                                                    .length() <= 0
                                                                                    && mTime.toString()
                                                                                            .length() <= 0) {

                                                                                setSingleReservation();
                                                                            }
                                                                            Log.i(TAG,
                                                                                    mDate.toString()
                                                                                            + ","
                                                                                            + mTime.toString());
                                                                        }
                                                                    })
                                                            .setNegativeButton(
                                                                    R.string.cancel,
                                                                    new DialogInterface.OnClickListener() {

                                                                        @Override
                                                                        public void onClick(
                                                                                DialogInterface dialog,
                                                                                int which) {
                                                                            dialog.dismiss();
                                                                        }
                                                                    }).create().show();
                                                } catch (Exception e) {
                                                    Log.e(TAG,
                                                            "set date and time dialog occurs exception, msg:"
                                                                    + e.getMessage());
                                                    Toast.makeText(getApplicationContext(),
                                                            "设置日期和时间对话框出错", Toast.LENGTH_SHORT)
                                                            .show();
                                                }

                                                // then close it
                                                dialog.dismiss();

                                            }
                                        }
                                    }).create().show();

                    return true;
                }

                return false;
            }
        });

        mStartPlaceFavorite.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.v(TAG, "StartPlaceFavorite ib clicked, gonna to startActivityForResult");

                try {
                    startActivityForResult(new Intent(ReservationActivity.this,
                            FavoriteAddressActivity.class), REQUEST_CODE_ADDRESS_START);
                } catch (Exception e) {
                    Log.w(TAG,
                            "startActivityForResult to FavoriteAddressActivity occurs exception. Message : "
                                    + e.getMessage());
                    Toast.makeText(ReservationActivity.this, "出错信息：" + e.getMessage(),
                            Toast.LENGTH_SHORT).show();

                    return;
                }
            }
        });

        mEndPlaceFavorite.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i(TAG, "EndPlaceFavorite ib clicked, gonna to startActivityForResult");

                try {
                    startActivityForResult(new Intent(ReservationActivity.this,
                            FavoriteAddressActivity.class), REQUEST_CODE_ADDRESS_END);
                } catch (Exception e) {
                    Log.w(TAG,
                            "startActivityForResult to FavoriteAddressActivity occurs exception. Message : "
                                    + e.getMessage());
                    Toast.makeText(ReservationActivity.this, "出错信息：" + e.getMessage(),
                            Toast.LENGTH_SHORT).show();

                    return;
                }
            }
        });
    }

    /**
     * Set the date and time of single reservation to mReservation
     */
    private void setSingleReservation() {
        mReservation.setText("");
        mReservation.setText("单次预约：");
        mReservation.append(mDate.toString() + "," + mTime.toString());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // onResume();
        switch (requestCode) {
            case REQUEST_CODE_ADDRESS_END:
                if (resultCode == RESULT_OK) {
                    String address;
                    Bundle resultBundle = data.getExtras();
                    if (resultBundle.containsKey(FavoriteAddress.TAG)) {
                        address = resultBundle.getString(FavoriteAddress.TAG);
                    } else {
                        break;
                    }
                    mEndPlace.setText(address);
                }
                break;
            case REQUEST_CODE_ADDRESS_START:
                if (resultCode == RESULT_OK) {
                    String address;
                    Bundle resultBundle = data.getExtras();
                    if (resultBundle.containsKey(FavoriteAddress.TAG)) {
                        address = resultBundle.getString(FavoriteAddress.TAG);
                    } else {
                        break;
                    }
                    mStartPlace.setText(address);
                }
                break;
            case REQUEST_CODE_CYCLE:
                if (resultCode == RESULT_OK) {
                    Bundle resultBundle = data.getExtras();
                    StringBuilder strCycle = new StringBuilder();

                    if (resultBundle.containsKey(ReservationCycle.TAG)) {
                        mCycle = (ReservationCycle) resultBundle
                                .getSerializable(ReservationCycle.TAG);
                    } else {
                        break;
                    }

                    strCycle.append("预约周期：");

                    if (mCycle.isAfternoon()) {
                        strCycle.append(ReservationCycle.AFTERNOON);
                        strCycle.append("，");
                    }

                    if (mCycle.isEveryDay()) {
                        strCycle.append(ReservationCycle.EVERY_DAY);
                        strCycle.append("，");
                    }

                    if (mCycle.isEveryMonth()) {
                        strCycle.append(ReservationCycle.EVERY_MONTH);
                        strCycle.append("，");
                    }

                    if (mCycle.isEveryYear()) {
                        strCycle.append(ReservationCycle.EVERY_YEAR);
                        strCycle.append("，");
                    }

                    if (mCycle.isWorkingDay()) {
                        strCycle.append(ReservationCycle.WORKING_DAY);
                        strCycle.append("，");
                    }
                    if (mCycle.isNonWorkingDay()) {
                        strCycle.append(ReservationCycle.NON_WORKING_DAY);
                        strCycle.append("，");
                    }
                    if (mCycle.isMorning()) {
                        strCycle.append(ReservationCycle.MORNING);
                        strCycle.append("，");
                    }
                    if (mCycle.isMondayToFriday()) {
                        strCycle.append(ReservationCycle.MONDAY_TO_FRIDAY);
                        strCycle.append("，");
                    }
                    if (mCycle.isWhatClock()) {
                        strCycle.append(mCycle.getWhatClock());
                        strCycle.append("，");
                    }

                    boolean isExceptional_weekend = mCycle.isExceptional_weekend();
                    boolean isExceptional_holiday = mCycle.isExceptional_holiday();
                    if (isExceptional_holiday || isExceptional_weekend) {
                        strCycle.append("{例外：");
                        if (isExceptional_holiday && !isExceptional_weekend) {
                            strCycle.append(ReservationCycle.EXCEPTIONAL_HOLIDAY);
                            strCycle.append("}");
                        }
                        if (!isExceptional_holiday && isExceptional_weekend) {
                            strCycle.append(ReservationCycle.EXCEPTIOANL_WEEKEND);
                            strCycle.append("}");
                        }
                        if (isExceptional_holiday && isExceptional_weekend) {
                            strCycle.append(ReservationCycle.EXCEPTIONAL_HOLIDAY);
                            strCycle.append(ReservationCycle.EXCEPTIOANL_WEEKEND);
                            strCycle.append("}");
                        }
                    }

                    if (strCycle.lastIndexOf("例外") == -1) {
                        int lastCommaIndex = strCycle.lastIndexOf("，");

                        // Delete the last comma
                        strCycle.deleteCharAt(lastCommaIndex);
                    }
                    mReservation.setText(strCycle);

                    // Toast.makeText(ReservationActivity.this, strCycle,
                    // Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
